//
//  ShareOrderActServiceViewController.m
//  ShangHaiHuDongApp
//
//  Created by 刘应平 on 2017/6/14.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "ShareOrderActServiceViewController.h"
#import "LPCostomLabelAndTextFieldAndImageView.h"
#import "ZJSIScopeView.h"
#import "LPCostomLabelAndTextViewAdaptHeightView.h"
#import "LPChooseOnlyHourAndMintueView.h"
#import "JCAlertView.h"
#import "LCustomAlertView.h"
#import "LPResouceRepeatTishiView.h"
@interface ShareOrderActServiceViewController ()<LPChooseYearAndMonthAndDayAndHourAndMinuteDelegate,LPCostomLabelAndTextFieldAndImageViewDelegate,LPResouceRepeatTishiDelegate,LPChooseOnlyHourAndMintueDelegate>
/**  开始时间  */
@property (strong, nonatomic) LPCostomLabelAndTextFieldAndImageView  *starttimeView;
/**  结束时间  */
@property (strong, nonatomic) LPCostomLabelAndTextFieldAndImageView  *endtimeView;
/**  姓名  */
@property (strong, nonatomic) LPCostomLabelAndTextFieldAndImageView  *name;

/** 手机号  */
@property (strong, nonatomic) LPCostomLabelAndTextFieldAndImageView  *phone;
/**  面向组织是输入组织名  */
@property (strong, nonatomic) LPCostomLabelAndTextFieldAndImageView  *orangize;

/** 人数  */
@property (strong, nonatomic) LPCostomLabelAndTextFieldAndImageView  *persoNumber;
/**  提交  */
@property (strong, nonatomic) UIButton  *sendButton;
/**  scrollView  */
@property (strong, nonatomic) UIScrollView  *backScrollView;


/**  备注  */
@property (strong, nonatomic) LPCostomLabelAndTextViewAdaptHeightView  *beizhu;
/**  时间选择  */
@property (strong, nonatomic)  LPChooseYearAndMonthAndDayAndHourAndMinuteView *pickTime;
/**  时间选择时分  */
@property (strong, nonatomic) LPChooseOnlyHourAndMintueView  *hourAndMintuesTime;

/**  时间选择判断选择是拿一个  */
@property (assign, nonatomic) NSInteger  timeTag;

/**  jc  */
@property (strong, nonatomic) JCAlertView  *alertView;

/**当前年月日   */
@property (strong, nonatomic) NSString  *currentDay;
/**  选择的年月日  */
@property (strong, nonatomic) NSString  *chooseDay;


@end

@implementation ShareOrderActServiceViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.currentDay = [NSDateFormatter stringWithDate:[NSDate date]];
    self.titlelabel.text = @"预约";
    if (self.isJFDH) {
        self.titlelabel.text = @"兑换";
    }
    [self.view addSubview:self.backScrollView];
    [self.backScrollView addSubview:self.name];
    [self.backScrollView addSubview:self.phone];
    if ([self.model.TORANG isEqualToString:@"1"]) {
        [self.backScrollView addSubview:self.orangize];
    }
    [self.backScrollView addSubview:self.persoNumber];
    [self.backScrollView addSubview:self.starttimeView];
    [self.backScrollView addSubview:self.endtimeView];
    [self.backScrollView addSubview:self.beizhu];
    [self.backScrollView addSubview:self.sendButton];
    
    self.backScrollView.contentSize = CGSizeMake(self.view.width, self.sendButton.bottom + 65 * [UIScreen zj_screenHScale]);
    
}

#pragma mark - LCustomAlertDelegate
- (void)lCustomAlertWithView:(LCustomAlertView *)view index:(NSInteger)index{
    
    
    //    [self.jcAlertView dismissWithCompletion:nil];
}

/**  发布活动 */
- (void)clickButton{
    if (self.name.secondTextField.text.length == 0) {
        [YJProgressHUD showSuccess:@"请输入姓名" inview:self.view];
         [self.name.secondTextField becomeFirstResponder];
        return;
    }
    if (self.phone.secondTextField.text.length == 0) {
        [YJProgressHUD showSuccess:@"请输入手机号" inview:self.view];

        [self.phone.secondTextField becomeFirstResponder];
        return;
    }
    if ([self.model.TORANG isEqualToString:@"1"]) {
        if (self.orangize.secondTextField.text.length == 0) {
            [YJProgressHUD showSuccess:@"请输入组织名" inview:self.view];

             [self.orangize.secondTextField becomeFirstResponder];
            return;
        }
    }
    if (self.persoNumber.secondTextField.text.length == 0) {
        [YJProgressHUD showSuccess:@"请输入预约数量" inview:self.view];
        [self.persoNumber.secondTextField becomeFirstResponder];
        return;
    }
    
    if (![self.model.PEOPLE_NUM isEqualToString:@"0"]) {
        if ([self.persoNumber.secondTextField.text integerValue] > [self.model.PEOPLE_NUM integerValue]) {
            NSString *content = [NSString stringWithFormat:@"超出容纳数量，无法预约，最多预约%@",self.model.PEOPLE_NUM];
            [YJProgressHUD showMessage:content inView:self.view afterDelayTime:3.f];
            [self.persoNumber.secondTextField becomeFirstResponder];
            return;
        }
    }
    
    
    if (self.starttimeView.secondTextField.text.length == 0) {
        [YJProgressHUD showSuccess:@"请选择开始时间" inview:self.view];

        return;
    }
    if (self.endtimeView.secondTextField.text.length == 0) {
        [YJProgressHUD showSuccess:@"请选择结束时间" inview:self.view];

        return;
    }
    
    NSInteger time = [NSDate returnMaxDateFormDate:[NSDateFormatter dateHourAndMintueWithString:self.endtimeView.secondTextField.text] lastFate:[NSDateFormatter dateHourAndMintueWithString:self.starttimeView.secondTextField.text]];
    
    if (time != 1) {
        [YJProgressHUD showSuccess:@"请选择正确的时间" inview:self.view];

        return;
    }
    
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *paramer = [NSMutableDictionary dictionary];
    paramer[@"USERNAME"] = self.name.secondTextField.text;
    paramer[@"USERPHONE"] = self.phone.secondTextField.text;
    paramer[@"NUM"] = self.persoNumber.secondTextField.text;
    paramer[@"ORDERDATE"] = [self.starttimeView.secondTextField.text substringToIndex:11];
    paramer[@"CONTENT"] = self.beizhu.adaptTextView.text.length != 0 ? self.beizhu.adaptTextView.text : @"";
    paramer[@"UNITID"] = ZJUSERINFORMODEL.CURRENT_DEPT_MODEL.ID;
    paramer[@"USERID"] = ZJUSERINFORMODEL.CURRENT_USER_MODEL.ID;
    paramer[@"ORDERBEGINTIME"] = [self.starttimeView.secondTextField.text substringFromIndex:11];
    paramer[@"ORDERENDTIME"] = [self.endtimeView.secondTextField.text substringFromIndex:11];
    paramer[@"RESOURCEID"] = self.model.ID;
    paramer[@"RESOURCETYPE"] = self.model.RESOURCETYPE;
    paramer[@"ONCE"] = @"";
    if ([self.model.TORANG isEqualToString:@"1"]) {
        paramer[@"ORG_NAME"] = self.orangize.secondTextField.text;
    }else{
        paramer[@"ORG_NAME"] = @"";
    }
    [YJProgressHUD showMessage:@"预约中..." duration:10 view:self.view];
    
    [NetWorkingManager postWithUrlString:[NetWorkingURL getpbactionAuditaddClime] Parameter:paramer Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            if ([[[object objectForKey:@"TOTAL"] objectForKey:@"TOTAL"] isEqualToString:@"0"]) {
                [MobClick event:[UMMStatisticsString reserveService]];
                [YJProgressHUD showSuccess:@"预约成功" inview:weakSelf.view];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
            }else{
                [YJProgressHUD hide];
                [weakSelf alertViewTishi:[object objectForKey:@"RESOURCEINFO"]];
            }
            
            
        }else{
            
            [YJProgressHUD showSuccess:@"预约失败" inview:weakSelf.view];
        }
    } Fail:^(id object) {
        [YJProgressHUD showSuccess:@"网络错误" inview:weakSelf.view];
    }];
    
    
}

#pragma mark - LPResouceRepeatTishiDelegate
- (void)LPResouceRepeatTishRemove_view{
    [self.alertView dismissWithCompletion:nil];
    [self.persoNumber.secondTextField becomeFirstResponder];
}

- (void)alertViewTishi:(NSArray *)array{
    /**  已经预约的资源人数的总数  */
    NSInteger number = 0;
    NSMutableArray *times = [NSMutableArray array];
    [times addObject:@"该资源于"];
    for (NSDictionary *tishi in array) {
        NSString *start = [tishi[@"ORDERBEGINTIME"] substringToIndex:5];
        NSString *end = [tishi[@"ORDERENDTIME"] substringToIndex:5];
        NSString *num = [tishi objectForKey:@"NUM"];
        NSString *time = [NSString stringWithFormat:@"%@-%@,已预约%@人",start,end,num];
        [times addObject:time];
        number += [[tishi objectForKey:@"NUM"] integerValue];
    }
    
    /**  已经预约加上当前预约人数的总数  */
    NSInteger total = number + [self.persoNumber.secondTextField.text integerValue];
    
    /**  这里根据预约人数判断，如果预约总人数超过最大预约人数，提示，并重新预约  */
    
    if (number == [self.model.PEOPLE_NUM integerValue]) {
        /**  这里已经预约人数和资源容纳的最大人数相同  */
        [times addObject:[NSString stringWithFormat:@"资源预约人数已达上限,请重新选择资源预约"]];
        LPResouceRepeatTishiView *tishiView = [[LPResouceRepeatTishiView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) array:times];
        tishiView.delegate = self;
        self.alertView = [[JCAlertView alloc] initWithCustomView:tishiView dismissWhenTouchedBackground:YES];
        [self.alertView show];
        
    }else{
        /**  这是小于资源容纳的最大人数  */
        if (total > [self.model.PEOPLE_NUM integerValue]) {
            [times addObject:[NSString stringWithFormat:@"您还可以预约%ld人,请重新预约",[self.model.PEOPLE_NUM integerValue]- number]];
            LPResouceRepeatTishiView *tishiView = [[LPResouceRepeatTishiView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) array:times];
            tishiView.delegate = self;
            self.alertView = [[JCAlertView alloc] initWithCustomView:tishiView dismissWhenTouchedBackground:YES];
            [self.alertView show];
            
        }else{
            /**  这里是未超过，预约成功  */
            [MobClick event:[UMMStatisticsString reserveService]];
            [YJProgressHUD showSuccess:@"预约成功" inview:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }
    
    }
    
   
    
   
    
}
#pragma mark - LPCostomLabelAndTextFieldAndImageViewDelegate
- (void)LPCostomLabelAndTextFieldAndImageWith:(LPCostomLabelAndTextFieldAndImageView *)view click:(BOOL)click{
    self.timeTag = view.tag;
    if (self.timeTag == 7) {
        [self.pickTime show:self.starttimeView.secondTextField.text];
    }else{
        NSString *time = [self.endtimeView.secondTextField.text substringFromIndex:11];
        [self.hourAndMintuesTime show:time];
    }
    
    
}

#pragma mark - LPCostomChooseYearAndMonthAndDayDelegate
- (void)ChooseYearAndMonthAndDayAndHourAndMinuteWithTitle:(NSString *)string{
    self.chooseDay = [string substringToIndex:11];
    self.starttimeView.secondTextField.text = string;
    NSString *end = [self.endtimeView.secondTextField.text substringFromIndex:11];
    self.endtimeView.secondTextField.text = [NSString stringWithFormat:@"%@%@",self.chooseDay,end];
}



#pragma mark - LPChooseOnlyHourAndMintueDelegate
- (void)LPChooseOnlyHourAndMintueWithTitle:(NSString *)string{
    if (self.chooseDay.length != 0) {
         self.endtimeView.secondTextField.text = [NSString stringWithFormat:@"%@%@",self.chooseDay,string];
    }else{
         self.endtimeView.secondTextField.text = [NSString stringWithFormat:@"%@ %@",self.currentDay,string];
    }
   
}


- (LPCostomLabelAndTextFieldAndImageView *)name{
    if (!_name) {
        _name = [[LPCostomLabelAndTextFieldAndImageView alloc] initWithFrame:CGRectMake(0,  40 * [UIScreen zj_screenHScale], self.view.width, 80 * [UIScreen zj_screenHScale]) title:@"姓名 :" placehold:@"请输入姓名" imageString:@""];
        _name.secondTextField.text = ZJUSERINFORMODEL.ORG_ACCOUNT.USER_NAME;
        _name.secondTextField.userInteractionEnabled = YES;
        _name.isShow = YES;
        _name.maxNumber = 50;
    }
    return _name;
}


- (LPCostomLabelAndTextFieldAndImageView *)phone{
    if (!_phone) {
        _phone = [[LPCostomLabelAndTextFieldAndImageView alloc] initWithFrame:CGRectMake(0,  self.name.bottom + 20 * [UIScreen zj_screenHScale], self.view.width, 80 * [UIScreen zj_screenHScale]) title:@"手机号 :" placehold:@"请输入手机号" imageString:@""];
        _phone.secondTextField.text = ZJUSERINFORMODEL.ORG_ACCOUNT.MOBILE;
        _phone.secondTextField.userInteractionEnabled = YES;
        _phone.secondTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _phone.isShow = YES;
        _phone.maxNumber = 11;
    }
    return _phone;
}


- (LPCostomLabelAndTextFieldAndImageView *)orangize{
    if (!_orangize) {
        _orangize = [[LPCostomLabelAndTextFieldAndImageView alloc] initWithFrame:CGRectMake(0,  self.phone.bottom + 20 * [UIScreen zj_screenHScale], self.view.width, 80 * [UIScreen zj_screenHScale]) title:@"组织名 :" placehold:@"输入组织名" imageString:@""];
        _orangize.secondTextField.text = ZJUSERINFORMODEL.DEPT_MODEL_BOOK.DEPTABBREVIATION ? ZJUSERINFORMODEL.DEPT_MODEL_BOOK.DEPTABBREVIATION :@"";
        _orangize.secondTextField.userInteractionEnabled = YES;
        _orangize.isShow = YES;
        _orangize.maxNumber = 50;
        
    }
    return _orangize;
}


- (LPCostomLabelAndTextFieldAndImageView *)persoNumber{
    if (!_persoNumber) {
        if ([self.model.TORANG isEqualToString:@"1"]) {
            
            _persoNumber = [[LPCostomLabelAndTextFieldAndImageView alloc] initWithFrame:CGRectMake(0,  self.orangize.bottom + 20 * [UIScreen zj_screenHScale], self.view.width, 80 * [UIScreen zj_screenHScale]) title:@"预约人数 :" placehold:@"请输入人数" imageString:@""];
            
        }else{
            _persoNumber = [[LPCostomLabelAndTextFieldAndImageView alloc] initWithFrame:CGRectMake(0,  self.phone.bottom + 20 * [UIScreen zj_screenHScale], self.view.width, 80 * [UIScreen zj_screenHScale]) title:@"预约人数 :" placehold:@"请输入人数" imageString:@""];
        }
        
        _persoNumber.secondTextField.userInteractionEnabled = YES;
        _persoNumber.secondTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _persoNumber.isShow = YES;
        _persoNumber.maxNumber = 50;
        
        if (self.isJFDH) {
            _persoNumber.secondTextField.placeholder = @"请输入数量";
            _persoNumber.firstLabel.text = @"兑换数量 :";
        }
        
    }
    return _persoNumber;
}

- (LPCostomLabelAndTextFieldAndImageView *)starttimeView{
    if (!_starttimeView) {
        _starttimeView = [[LPCostomLabelAndTextFieldAndImageView alloc] initWithFrame:CGRectMake(0, self.persoNumber.bottom + 20 * [UIScreen zj_screenHScale], self.view.width, 80 * [UIScreen zj_screenHScale]) title:@"开始时间 :" placehold:@"请选择开始时间" imageString:@"icon_calendar"];
        _starttimeView.delegate = self;
        _starttimeView.secondTextField.text = [NSString stringWithFormat:@"%@ 09:00",self.currentDay];
        _starttimeView.isShow = YES;
        _starttimeView.tag = 7;
        
    }
    return _starttimeView;
}

- (LPCostomLabelAndTextFieldAndImageView *)endtimeView{
    if (!_endtimeView) {
        _endtimeView = [[LPCostomLabelAndTextFieldAndImageView alloc] initWithFrame:CGRectMake(0, self.starttimeView.bottom + 20 * [UIScreen zj_screenHScale], self.view.width, 80 * [UIScreen zj_screenHScale]) title:@"结束时间 :" placehold:@"请选择结束时间" imageString:@"icon_calendar"];
        _endtimeView.secondTextField.text = [NSString stringWithFormat:@"%@ 18:00",self.currentDay];
        _endtimeView.delegate = self;
        _endtimeView.isShow = YES;
        _endtimeView.tag = 8;
    }
    return _endtimeView;
}


- (LPCostomLabelAndTextViewAdaptHeightView *)beizhu{
    if (_beizhu == nil) {
        _beizhu = [[LPCostomLabelAndTextViewAdaptHeightView alloc] initWithFrame:CGRectMake(0, self.endtimeView.bottom + 20 * [UIScreen zj_screenHScale], self.view.width, 200 * [UIScreen zj_screenHScale]) title:@"备注 :" textViewHeight:160 * [UIScreen zj_screenHScale]];
        _beizhu.maxNumber = 200;
    }
    return _beizhu;
}


- (UIButton *)sendButton{
    if (!_sendButton) {
        _sendButton = ({
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(40 * [UIScreen zj_screenWScale], self.beizhu.bottom + 40 * [UIScreen zj_screenHScale], self.view.width - 80 * [UIScreen zj_screenWScale], 50 * [UIScreen zj_screenHScale])];
            [button setTitle:@"提交" forState:UIControlStateNormal];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            button.titleLabel.textAlignment = NSTextAlignmentCenter;
            button.titleLabel.font = LYPFONT(15);
            button.backgroundColor = [UIColor themeColor];
            [button addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside];
            button.layer.cornerRadius = 3;
            button.layer.masksToBounds = YES;
            button;
            
        });
    }
    return _sendButton;
}

- (UIScrollView *)backScrollView{
    if (!_backScrollView) {
        _backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, LP_TopHeight, self.view.width, self.view.height - LP_TopHeight )];
        _backScrollView.contentOffset = CGPointMake(0, 0);
        _backScrollView.showsVerticalScrollIndicator = NO;
    }
    return _backScrollView;
    
}




- (LPChooseYearAndMonthAndDayAndHourAndMinuteView *)pickTime{
    if (!_pickTime) {
        _pickTime  = [[LPChooseYearAndMonthAndDayAndHourAndMinuteView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
        _pickTime.delegate = self;
    }
    return _pickTime;
}

- (LPChooseOnlyHourAndMintueView *)hourAndMintuesTime{
    if (!_hourAndMintuesTime) {
        _hourAndMintuesTime  = [[LPChooseOnlyHourAndMintueView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
        _hourAndMintuesTime.delegate = self;
    }
    return _hourAndMintuesTime;
}


@end
